package com.xxx.control.widget

import android.content.Context
import android.os.Handler
import android.os.Message
import android.text.SpannableStringBuilder
import android.util.AttributeSet
import com.blankj.utilcode.util.LogUtils

/**
 * Create by Sxl on 2023/7/19.
 */
class DelayAutoCompleteTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : androidx.appcompat.widget.AppCompatAutoCompleteTextView(context, attrs) {


    var autoCompleteDelay: Long = DEFAULT_AUTOCOMPLETE_DELAY

    val delayHandler: Handler = DelayHandler(this)

    internal class DelayHandler(val textView: DelayAutoCompleteTextView) : Handler() {
        override fun handleMessage(msg: Message) {
            var obj = msg?.obj

            var text: String = ""
            if (obj is SpannableStringBuilder) {
                text = obj.toString()
            } else if (obj is String) {
                text = obj
            }
            textView.performFiltering(text, msg?.arg1 ?: 0)
            LogUtils.e("handleMessage:$text")
        }
    }

    companion object {
        val MESSAGE_TEXT_CHANGES = 100
        val DEFAULT_AUTOCOMPLETE_DELAY: Long = 750

    }

    override fun performFiltering(text: CharSequence?, keyCode: Int) {
        super.performFiltering(text, keyCode)
        LogUtils.e("performFiltering")
        delayHandler.removeMessages(MESSAGE_TEXT_CHANGES)
        delayHandler.sendMessageDelayed(
            delayHandler.obtainMessage(MESSAGE_TEXT_CHANGES, text),
            autoCompleteDelay
        )
    }


    override fun onFilterComplete(count: Int) {
        super.onFilterComplete(count)
    }


    fun setDelay(millis: Long) {
        autoCompleteDelay = millis
    }
}